//
//  ViewController.swift
//  pibar
//
//  Created by apple on 2025/2/27.
//

import Cocoa

class ViewController: NSViewController, URLSessionWebSocketDelegate {
    private var priceLabels: [String: NSTextField] = [:]
    private var webSocket: URLSessionWebSocketTask?
    internal var selectedTokens: Set<String> = ["PI-USDT", "DOGE-USDT", "BTC-USDT"] // 默认显示的代币
    private var tokenIcons: [String: NSImage] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("ViewController viewDidLoad")
        setupTouchBar()
        setupTokenIcons()  // 加载代币图标
        setupWebSocket()
        
        // 隐藏主窗口
        if let window = view.window {
            window.orderOut(nil)
        }
    }
    
    override func viewDidAppear() {
        super.viewDidAppear()
        print("ViewController viewDidAppear")
        self.view.window?.makeFirstResponder(self)
        
        // 隐藏主窗口
        if let window = view.window {
            window.orderOut(nil)
        }
    }
    
    private func setupTouchBar() {
        print("Setting up Touch Bar")
        if let touchBar = makeTouchBar() {
            if let identifier = NSTouchBarItem.Identifier.piPrice.rawValue as String? {
                DFRElementSetControlStripPresenceForIdentifier(identifier, true)
            }
            NSApplication.shared.touchBar = touchBar
            
            // 确保触控栏显示
            if let identifier = NSTouchBarItem.Identifier.piPrice.rawValue as String? {
                DFRSystemModalShowsCloseBoxWhenFrontMost(false)
                NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
            }
        }
        print("Touch Bar setup completed")
    }
    
    private func setupWebSocket() {
        print("Setting up WebSocket...")
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
        let url = URL(string: "wss://ws.okx.com:8443/ws/v5/public")!
        webSocket = session.webSocketTask(with: url)
        webSocket?.resume()
        
        // 添加心跳包
        startPing()
        
        subscribeToSelectedTokens()
    }
    
    private func subscribeToSelectedTokens() {
        print("Subscribing to tokens: \(selectedTokens)")  // 添加日志
        
        let args: [[String: String]] = selectedTokens.map { [
            "channel": "tickers",
            "instId": $0
        ] }
        
        let subscribeMessage: [String: Any] = [
            "op": "subscribe",
            "args": args
        ]
        
        guard let jsonData = try? JSONSerialization.data(withJSONObject: subscribeMessage),
              let jsonString = String(data: jsonData, encoding: .utf8) else {
            print("Failed to create subscription message")  // 添加错误日志
            return
        }
        
        print("Sending subscription message: \(jsonString)")  // 添加日志
        
        let message = URLSessionWebSocketTask.Message.string(jsonString)
        webSocket?.send(message) { error in
            if let error = error {
                print("WebSocket subscription error: \(error)")
            } else {
                print("Successfully sent subscription message")  // 添加成功日志
            }
        }
        
        // 开始接收消息
        receiveMessage()
    }
    
    private func receiveMessage() {
        webSocket?.receive { [weak self] result in
            switch result {
            case .success(let message):
                switch message {
                case .string(let text):
                    self?.handleWebSocketMessage(text)
                case .data(let data):
                    if let text = String(data: data, encoding: .utf8) {
                        self?.handleWebSocketMessage(text)
                    }
                @unknown default:
                    break
                }
                // 继续接收下一条消息
                self?.receiveMessage()
            case .failure(let error):
                print("WebSocket receive error: \(error)")
                // 5秒后尝试重新连接
                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                    self?.setupWebSocket()
                }
            }
        }
    }
    
    private func handleWebSocketMessage(_ text: String) {
        print("Received message: \(text)")  // 保留现有日志
        
        guard let data = text.data(using: .utf8),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
            print("Failed to parse message as JSON")  // 添加错误日志
            return
        }
        
        // 处理 pong 消息
        if let event = json["event"] as? String, event == "pong" {
            print("Received pong message")
            return
        }
        
        // 处理价格更新消息
        guard let dataArray = json["data"] as? [[String: Any]],
              let firstTicker = dataArray.first,
              let instId = firstTicker["instId"] as? String,
              let lastPrice = firstTicker["last"] as? String,
              let price = Double(lastPrice) else {
            print("Failed to extract price data from message")  // 添加错误日志
            return
        }
        
        print("Updating price for \(instId): \(price)")  // 添加更新日志
        
        DispatchQueue.main.async {
            self.updateTouchBarLabel(for: instId, with: price)
        }
    }
    
    private func updateTouchBarLabel(for token: String, with price: Double) {
        if let label = priceLabels[token] {
            let formattedPrice = String(format: "%.4f", price)
            label.stringValue = "$\(formattedPrice)"
        }
    }
    
    private func getTokenIcon(for token: String) -> NSImage? {
        let symbol = token.components(separatedBy: "-")[0].lowercased()
        
        // 临时使用系统图标，后面我们会替换成从 CoinGecko 获取的图标
        switch symbol {
        case "doge":
            return NSImage(systemSymbolName: "d.circle.fill", accessibilityDescription: nil)
        case "pi":
            return NSImage(systemSymbolName: "p.circle.fill", accessibilityDescription: nil)
        default:
            return NSImage(systemSymbolName: "dollarsign.circle.fill", accessibilityDescription: nil)
        }
    }
    
    private func getTokenColor(for token: String) -> NSColor {
        switch token.components(separatedBy: "-")[0].lowercased() {
        case "doge":
            return .systemYellow
        case "pi":
            return .systemBlue
        default:
            return .systemGray
        }
    }
    
    deinit {
        // 关闭 WebSocket 连接
        webSocket?.cancel(with: .goingAway, reason: nil)
        if let identifier = NSTouchBarItem.Identifier.piPrice.rawValue as String? {
            DFRElementSetControlStripPresenceForIdentifier(identifier, false)
        }
    }
    
    // MARK: - URLSessionWebSocketDelegate
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
        print("WebSocket connected")
    }
    
    func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
        print("WebSocket closed")
        // 5秒后尝试重新连接
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            self.setupWebSocket()
        }
    }
    
    // MARK: - Token Management
    func addToken(_ token: String) {
        selectedTokens.insert(token)
        updateTouchBar()
        reconnectWebSocket()
    }
    
    func removeToken(_ token: String) {
        selectedTokens.remove(token)
        updateTouchBar()
        reconnectWebSocket()
    }
    
    private func updateTouchBar() {
        if let touchBar = self.touchBar {
            touchBar.defaultItemIdentifiers = selectedTokens.map { NSTouchBarItem.Identifier(rawValue: $0) }
            NSApplication.shared.touchBar = touchBar
            
            // 确保触控栏重新显示
            if let identifier = NSTouchBarItem.Identifier.piPrice.rawValue as String? {
                DFRSystemModalShowsCloseBoxWhenFrontMost(false)
                NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
            }
        }
    }
    
    private func reconnectWebSocket() {
        webSocket?.cancel(with: .goingAway, reason: nil)
        setupWebSocket()
    }
    
    // 添加新方法用于重新显示触控栏
    func reactivateTouchBar() {
        print("Reactivating Touch Bar")
        if let touchBar = self.touchBar {
            if let identifier = NSTouchBarItem.Identifier.piPrice.rawValue as String? {
                DFRSystemModalShowsCloseBoxWhenFrontMost(false)
                NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
            }
        }
    }
    
    private func loadTokenIcon(for token: String) {
        let symbol = token.components(separatedBy: "-")[0].lowercased()
        
        // 使用 OKX 的图标 URL
        let iconUrlString: String
        switch symbol {
        case "pi":
            iconUrlString = "https://www.okx.com/cdn/oksupport/asset/currency/icon/pi.png"
        case "doge":
            iconUrlString = "https://www.okx.com/cdn/oksupport/asset/currency/icon/doge.png?x-oss-process=image/format,webp"
        case "btc":
            iconUrlString = "https://www.okx.com/cdn/oksupport/asset/currency/icon/btc.png"
        default:
            return
        }
        
        guard let iconUrl = URL(string: iconUrlString) else { return }
        
        URLSession.shared.dataTask(with: iconUrl) { [weak self] data, response, error in
            guard let self = self,
                  let data = data,
                  let image = NSImage(data: data) else {
                return
            }
            
            DispatchQueue.main.async {
                self.tokenIcons[token] = image
                // 更新图标
                if let touchBar = self.touchBar {
                    touchBar.defaultItemIdentifiers.forEach { identifier in
                        if identifier.rawValue == token {
                            if let item = touchBar.item(forIdentifier: identifier) as? NSCustomTouchBarItem,
                               let containerView = item.view as? NSView,
                               let imageView = containerView.subviews.first(where: { $0 is NSImageView }) as? NSImageView {
                                imageView.image = image
                            }
                        }
                    }
                }
            }
        }.resume()
    }
    
    private func setupTokenIcons() {
        for token in selectedTokens {
            loadTokenIcon(for: token)
        }
    }
    
    private func startPing() {
        Timer.scheduledTimer(withTimeInterval: 15.0, repeats: true) { [weak self] _ in
            let message = URLSessionWebSocketTask.Message.string("{\"op\": \"ping\"}")
            self?.webSocket?.send(message) { error in
                if let error = error {
                    print("Ping error: \(error)")
                }
            }
        }
    }
}

// MARK: - NSTouchBarDelegate
extension ViewController: NSTouchBarDelegate {
    override func makeTouchBar() -> NSTouchBar? {
        let touchBar = NSTouchBar()
        touchBar.delegate = self
        touchBar.defaultItemIdentifiers = selectedTokens.map { NSTouchBarItem.Identifier(rawValue: $0) }
        touchBar.customizationAllowedItemIdentifiers = touchBar.defaultItemIdentifiers
        return touchBar
    }
    
    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
        let customItem = NSCustomTouchBarItem(identifier: identifier)
        
        let containerView = NSView(frame: NSRect(x: 0, y: 0, width: 130, height: 30))  // 增加宽度
        
        // 创建图标视图
        let imageView = NSImageView(frame: NSRect(x: 8, y: 3, width: 24, height: 24))
        imageView.imageScaling = .scaleProportionallyUpOrDown
        
        // 使用缓存的图标或默认系统图标
        if let cachedIcon = tokenIcons[identifier.rawValue] {
            imageView.image = cachedIcon
        } else {
            imageView.image = NSImage(systemSymbolName: "bitcoinsign.circle", accessibilityDescription: nil)
        }
        
        // 创建价格标签
        let label = NSTextField(frame: NSRect(x: 38, y: 5, width: 84, height: 20))  // 增加标签宽度
        label.isBezeled = false
        label.drawsBackground = false
        label.isEditable = false
        label.font = .systemFont(ofSize: 15)
        label.textColor = .white
        label.alignment = .left
        label.lineBreakMode = .byTruncatingTail
        label.stringValue = "Loading..."
        
        // 保存价格标签的引用
        priceLabels[identifier.rawValue] = label
        
        containerView.addSubview(imageView)
        containerView.addSubview(label)
        
        customItem.view = containerView
        return customItem
    }
}

// MARK: - Touch Bar Item Identifiers
extension NSTouchBarItem.Identifier {
    static let piPrice = NSTouchBarItem.Identifier("com.yourapp.touchbar.piprice")
}

